package com.sky.utils;

import com.sky.constant.NettyConstant;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RedisHashUtils {

    @Resource
    private RedisTemplate redisTemplate;

    private static RedisHashUtils redisHashUtils;

    @PostConstruct
    public void init(){
        redisHashUtils = this;
        redisHashUtils.redisTemplate = this.redisTemplate;
    }

    public static void hashSet(String key,String hashKey,Object value){
        redisHashUtils.redisTemplate.opsForHash().put(key,hashKey,value);
    }

    public static Object hashGet(String key,String hashKey){
        return redisHashUtils.redisTemplate.opsForHash().get(key,hashKey);
    }

    public static Map hashGetMap(String key){
        return redisHashUtils.redisTemplate.opsForHash().entries(key);
    }

    public static void hashDel(String key,String hashKey){
        redisHashUtils.redisTemplate.opsForHash().delete(key,hashKey);
    }


    /** 清除netty服务器上面的所有缓存 **/
    public static void clearNettyCache(String serverUrl) {
        // 通过netty服务器url查询该服务器上面的所有用户连接通道
        Map entries = redisHashUtils.redisTemplate.opsForHash().entries(NettyConstant.USER_SERVER_CACHE);
        if (StringUtils.isNotEmpty(entries)) {
            // 遍历所有用户连接通道
            entries.forEach((k, v) -> {
                String userId = k.toString();
                // 用户对应的netty地址服务器
                String userServerUrl = v.toString();
                if (serverUrl.equals(userServerUrl)){
                    hashDel(NettyConstant.USER_SERVER_CACHE, userId);
                    hashDel(NettyConstant.USER_CHANNEL_CACHE, userId);
                }
            });
        }
    }
}
